import Vue from 'vue'
import VueRouter from 'vue-router'
import {} from '../request/api'
import store from '../store'
// import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component:()=>import(/* webpackChunkName: "login" */ '../views/login/Login.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component:()=>import(/* webpackChunkName: "login" */ '../views/homepage/Home.vue')
  },
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to,from,next)=>{
  let token=localStorage.getItem('token')
  if(to.path!='/login'&&token&& !(to.path=='/home'&&from.path=='/login')){
    // 发送请求
    getUserByToken().then(res=>{
      if(res.errno===0){
        store.commit("SaveMenu",res.data.menu)
        next()
      }else{
        // 失败
        localStorage.clear()
        next('/login')
      }
    })
  }else{
    next()
  }
})

export default router
